package com.ccnode.codegenerator.taikaoback.service;

import com.ccnode.codegenerator.taikaoback.config.SpugSmsConfig;
import com.ccnode.codegenerator.taikaoback.security.jwt.SmsCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 短信服务
 */
@Service
public class SmsService {

    private static final Logger logger = LoggerFactory.getLogger(SmsService.class);

    @Autowired
    private SpugSmsConfig spugSmsConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送短信验证码
     * @param phoneNumber 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendSmsCode(String phoneNumber, String code) {
        try {
            // 构建请求URL
            String url = String.format("%s%s?code=%s&targets=%s",
                    spugSmsConfig.getApiUrl(),
                    spugSmsConfig.getTemplateId(),
                    code,
                    phoneNumber);

            logger.info("准备发送短信验证码，手机号：{}，验证码：{}", phoneNumber, code);
            logger.info("发送短信验证码请求URL：{}", url);

            // 调用Spug接口
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                logger.info("短信验证码发送成功，手机号：{}", phoneNumber);
                return true;
            } else {
                logger.error("短信验证码发送失败，状态码：{}，响应：{}",
                        response.getStatusCode(), response.getBody());
                return false;
            }
        } catch (Exception e) {
            logger.error("发送短信验证码异常，手机号：{}", phoneNumber, e);
            return false;
        }
    }

    /**
     * 发送6位短信验证码
     * @param phoneNumber 手机号
     * @return 生成的验证码，如果发送失败返回null
     */
    public String sendSixDigitSmsCode(String phoneNumber) {
        String code = SmsCodeUtil.generateSixDigitCode();
//        boolean success = sendSmsCode(phoneNumber, code);
        boolean success = true;
        return success ? code : null;
    }

    /**
     * 发送4位短信验证码
     * @param phoneNumber 手机号
     * @return 生成的验证码，如果发送失败返回null
     */
    public String sendFourDigitSmsCode(String phoneNumber) {
        String code = SmsCodeUtil.generateFourDigitCode();
        boolean success = sendSmsCode(phoneNumber, code);
        return success ? code : null;
    }
}